package leetcode100;

import java.util.ArrayList;
import java.util.List;

public class lc031 {
    public static void main(String[] args) {
        int n=3;
        List<String> res = new lc031().generateParenthesis(n);
        System.out.println("res = " + res);


        res.stream().forEach(System.out::println);
    }

    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();

        backtrace(res,new StringBuffer(),0,0,n);

        return res;
    }

    public void backtrace (List<String> res,StringBuffer current,int open,int close,int max) {
        if (current.length()==max*2) {
            res.add(current.toString());
            return ;
        }

        if (open<max) {
            backtrace(res,current.append("("),open+1,close,max);
            current.deleteCharAt(current.length()-1);
        }

        if (close<open) {
            backtrace(res,current.append(")"),open,close+1,max);
            current.deleteCharAt(current.length()-1);
        }

    }
}
